package com.woniuxy.configer;


import com.woniuxy.dao.ProjectUrlDao;
import com.woniuxy.filter.RoleUrlFilter;
import com.woniuxy.service.impl.FileHandler;
import com.woniuxy.service.impl.SuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private ProjectUrlDao projectUrlDao;

    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    public CorsConfigurationSource getCorsFilter() {
        UrlBasedCorsConfigurationSource cfs = new UrlBasedCorsConfigurationSource();
        CorsConfiguration cors = new CorsConfiguration();
        cors.addAllowedOriginPattern("*");
        cors.addAllowedMethod("*");
        cors.setAllowCredentials(true);
        cors.addAllowedHeader("*");
        cfs.registerCorsConfiguration("/**", cors);
        //CorsFilter cf = new CorsFilter(cfs);
        return cfs;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable()
                .csrf().disable()
                .addFilterAfter(new RoleUrlFilter(), FilterSecurityInterceptor.class)
                .authorizeRequests()
                .antMatchers("/account/nologin","/login","/swagger-ui.html","/v2/api-docs","/webjars/**",
                        "/swagger-resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/account/nologin")
                .loginProcessingUrl("/login")
                .successHandler(new SuccessHandler(projectUrlDao))
                .failureHandler(new FileHandler())
                .and()
                .cors().configurationSource(getCorsFilter());
    }


}
